import { AppState } from 'react-native';

class AppStateUtils {
  constructor() {
    this.appState = AppState.currentState;
    this.callbacks = [];
  }

  addChangeEventListener() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  removeChangeEventListener() {
    AppState.removeEventListener('change', this._handleAppStateChange);
    this.callbacks = [];
  }

  setChangeEventCallback(callback) {
    this.callbacks.push(callback);
  }

  _handleAppStateChange = nextAppState => {
    if (
      this.appState.match(/inactive|background/) &&
      nextAppState === 'active'
    ) {
      console.log('App has come to the foreground!');
      for (let callback of this.callbacks) {
        callback && callback(this.lastTime);
      }
    } else {
      // 记录当前进入后台时的时间
      this.lastTime = Date.now();
    }
    this.appState = nextAppState;
  };
}

AppStateUtils = new AppStateUtils();

export default AppStateUtils;
